package com.wh.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.basic.services.impl.FastDfsServiceImpl;
import com.wh.basic.utils.BaiduAuditUtils;
import com.wh.org.dao.IEmployeeDao;
import com.wh.org.dao.IShopAuditLogDao;
import com.wh.org.dao.ShopDao;
import com.wh.org.dto.ShopDto;
import com.wh.org.exception.BusinessException;
import com.wh.org.pojo.Employee;
import com.wh.org.pojo.Shop;
import com.wh.org.pojo.ShopAuditLog;
import com.wh.org.service.IShopService;
import com.wh.user.dao.LoginInfoDao;
import com.wh.user.pojo.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Service
public class ShopServiceImpl implements IShopService {
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    private IShopAuditLogDao shopAuditLogDao;
    @Autowired
    private IEmployeeDao employeeMapper;

    @Autowired
    private FastDfsServiceImpl fastDfsService;
    //获取邮件发件人
    @Value("${spring.mail.username}")
    private String mimeMessageFrom;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LoginInfoDao loginInfoDao;


    @Override
    public void add(Shop shop) {
        shopDao.insert(shop);
    }

    @Override
    public void del(Long id) {
        shopDao.deleteById(id);
    }

    @Override
    public void upd(Long id) {
        Shop shop = new Shop();
        shopDao.updateById(shop);
    }
    @Override
    public void patchDel(Long[] ids) {
//        dao.del(ids);
        shopDao.deleteBatchIds(Arrays.asList(ids));
    }
    @Override
    public List<Shop> findAll() {
        return shopDao.selectList(null);
    }

    @Override
    public Shop findById(Long id) {
        return shopDao.selectById(id);
    }



    @Override
    public IPage<Shop> findByPage(ShopDto shopDto) {
        //1.创建查询条件
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.like("name",shopDto.getKeyword());
        qw.or();
        qw.like("id",shopDto.getKeyword());
        //2.创建分页参数
        IPage<Shop> page = new Page<>(shopDto.getCurrentPage(),shopDto.getPageSize());
        //3.查询数据
        page.setRecords(shopDao.findByPage(page, qw));
        page.setTotal(shopDao.selectCount(qw));
//        List<Shop> list = (List<Shop>) dao.findByPage(page, qw);
//        IPage<Shop> page1 = page.setRecords(list);
        //4.返回结果
        return page;

    }


    /**
     *店铺注册的AI审核和人工审核
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {

//        //0.使用百度AI智能审核
//        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
//            throw new BusinessException("店铺名称不合法!!!");
//        }
//        byte[] imgBys = fastDfsService.downloadFile(shop.getLogo());
//        if (!ObjectUtil.isEmpty(imgBys)){
//            if (!BaiduAuditUtils.ImgCensor(imgBys)) {
//                throw new BusinessException("店铺LOGO不合法!!!");
//            }
//        }
//
//        //1 先获取 店长/管理员
//        if (StrUtil.isBlank(shop.getAdmin().getUsername()) ||
//             StrUtil.isBlank(shop.getAdmin().getPhone())){
//            throw new BusinessException("管理员信息不能为空");
//        }
//        //2.校验 - 当前店铺是否入驻过【地址和名称都一样就是入驻过】
//        QueryWrapper<Shop> qw1 = new QueryWrapper<>();
//        qw1.eq("address",shop.getAddress());
//        qw1.eq("name",shop.getName());
//        Shop shop1 = shopDao.selectOne(qw1);
//            //判断shop1中是否有数据
//        if (shop1!=null){
//            throw new BusinessException("店铺已经入驻过，请直接登录。如果忘记密码，请联系管理员!!!");
//        }
//        //3 可以添加 ： 先添加管理员（用户） 再添加店铺
//        Employee admin = shop.getAdmin();
//        //3.2 添加管理员信息 - 生成32位随机盐值
//        String uuid = RandomUtil.randomString(32);
//        admin.setSalt(uuid);
//        //3.3 添加管理员信息 - 对密码进行加盐加密处理
//        String md5Pwd = SecureUtil.md5(admin.getPassword() + uuid);
//        admin.setPassword(md5Pwd);
//
//        //添加logininfo信息
//        LoginInfo logininfo = new LoginInfo();
//        BeanUtil.copyProperties(admin,logininfo);
//        logininfo.setType(0);//管理员
//        logininfo.setDisable(true);//可以登陆
//        loginInfoDao.insert(logininfo);
//        admin.setLogininfoId(logininfo.getId());
//
//        //3.4 添加管理员信息
//        admin.setState(1);
//        //3.5 添加管理员信息（添加后自动生成主键）
//        employeeDao.insert(admin);
//
//        //4.添加店铺信息到数据库
//        //4.1 将管理员id设置到shop对象
//        shop.setAdminId(admin.getId());
//        shop.setRegisterTime(new Date());
//        shop.setState(1);
//
//        //添加店铺
//        shopDao.insert(shop);
//
//        //把店铺信息关联到用户
//        admin.setShopId(shop.getId());
//        employeeDao.updateById(admin);
    }

    /**
     * 审核通过
     * @param shopAuditLog
     */
    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
//        //1.修改店铺状态
//        shopDao.updateById(new Shop().setState(2).setId(shopAuditLog.getShopId()));
//        //2.保存审核日志
//        shopAuditLog.setState(2).setAuditTime(LocalDateTime.now());
//        shopAuditLogDao.insert(shopAuditLog);
//        //3.发送激活邮件
//        try {
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//            helper.setFrom(mimeMessageFrom);
//            helper.setSubject("【宠物之家】店铺激活邮件");
//            //true - 能够再内容中编写html标签 - 会解析
//            helper.setText("<h3>你的店铺已经审核通过，请<a href='http://127.0.0.1:8080/active/" + shopAuditLog.getShopId()
//                    + "'>点击这里</a>激活邮件</h3>", true);
//            //获取店铺的店长信息
//            QueryWrapper<Employee> qw = new QueryWrapper<>();
//            qw.eq("shop_id",shopAuditLog.getShopId());
//            Employee admin = employeeMapper.selectOne(qw);
//            helper.setTo(admin.getEmail());
//            //发送
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            throw new BusinessException("邮件发送失败!");
//        }
    }

    /**
     * 驳回店铺申请,并发送邮件
     * @param shopAuditLog 审核日志
     */
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
//        //1.改状态 保存审核日志 发邮件
//        shopDao.updateById(new Shop().setState(4).setId(shopAuditLog.getShopId()));
//
//        //2.保存审核日志
//        shopAuditLog.setState(4).setAuditTime(LocalDateTime.now());
//        shopAuditLogDao.insert(shopAuditLog);
//
//        //3.发邮件
//        try {
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//            helper.setFrom(mimeMessageFrom);
//            helper.setSubject("【宠物之家】店铺激活失败通知");
//            //true - 能够再内容中编写html标签 - 会解析
//            helper.setText("<h3>你的店铺审核未通过，请<a href='http://127.0.0.1:8081/#/ShopRegisterEdit/" + shopAuditLog.getShopId()
//                    + "'>点击这里</a>修改入驻信息重新提交</h3>", true);
//            //获取店铺的店长信息
//            QueryWrapper<Employee> qw = new QueryWrapper<>();
//            qw.eq("shop_id", shopAuditLog.getShopId());
//            Employee admin = employeeMapper.selectOne(qw);
//            helper.setTo(admin.getEmail());
//            //发送
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            throw new BusinessException("驳回邮件发送失败!");
//        }
    }

    @Override
    public void updateState(Shop shop) {
        shopDao.updateById(shop);
    }
}
